/** @format */

import { connect, Connection, Channel } from 'amqplib';

const AMQP_SERVIC = 'amqp://gj:123qwe@10.0.0.215:5672';
const RECORD_MQ_EXCHANGE = 'recordMQ';
const RECORD_MQ_EXCHANGE_TYPE = 'topic';
let index = 0;

const msgs: Array<string> = [
    'init.1.record',
    'init.2.record',
    'init.3.record',
    'UI.1.delete',
    'UI.4.add',
    'UI.3.delete',
    'UI.4.delete',
    'UI.2.delete',
];

let amqp: Connection | undefined = undefined;
let channel: Channel | undefined = undefined;

async function init(): Promise<void> {
    amqp = await connect(AMQP_SERVIC);
    channel = await amqp.createChannel();
}

async function bootstrap(): Promise<void> {
    await init();
    if (channel) {
        await channel.assertExchange(RECORD_MQ_EXCHANGE, RECORD_MQ_EXCHANGE_TYPE, {
            // durable?: boolean;
            // internal?: boolean;
            // autoDelete?: boolean;
            // alternateExchange?: string;
            // arguments?: any;
            durable: true, // 持久
            autoDelete: false, //自动删除
        });
        const interval = setInterval(async () => {
            if (index < msgs.length) {
                const routingKey = msgs[index];
                const currentMsg = `[${Date.now()}][${index}][${msgs[index]}]`;
                console.log(`<${routingKey}>:${currentMsg}`);
                if (channel) {
                    channel.publish(RECORD_MQ_EXCHANGE, routingKey, Buffer.from(currentMsg));
                }
                index++;
            } else {
                if (channel) {
                    await channel.close();
                    channel = undefined;
                }
                if (amqp) {
                    await amqp.close();
                    amqp = undefined;
                }
                clearInterval(interval);
            }
        }, 1000);
    }
}
bootstrap();
